<template>
  <a-modal
    v-model:visible="formVisible"
    :title="getTitle"
    @ok="handleModalOK"
    @cancel="handleModalCancel"
    :confirm-loading="confirmLoading"
  >
    <a-form :model="formData" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
      <a-form-item v-bind="validateInfos.name" label="角色名">
        <a-input v-model:value="formData.name" />
      </a-form-item>
      <a-form-item label="状态" v-bind="validateInfos.status">
        <a-radio-group v-model:value="formData.status">
          <a-radio :value="1">正常</a-radio>
          <a-radio :value="2">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model:value="formData.description" :auto-size="{ minRows: 2, maxRows: 5 }" />
      </a-form-item>

      <a-form-item label="权限">
        <a-tree
          checkable
          checkStrictly
          v-model:checkedKeys="checkedKeys"
          @check="handlePermChecked"
          :tree-data="permissionTreeData"
          :field-names="{
            children: 'children',
            title: 'title',
            key: 'id',
          }"
        >
        </a-tree>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
export default {
  name: 'RoleModal',
};
</script>
<script setup lang="ts">
import { ref, computed, onMounted, watch, unref } from 'vue';
import { getPermissionList, getPermissionListByRole, addRole, updateRole } from '/@/api/sys/system';
import { deepMerge } from '/@/utils/index';
import { Form, message } from 'ant-design-vue';
const useForm = Form.useForm;

const props = defineProps({
  visible: Boolean,
  data: Object,
});
const emit = defineEmits(['ok', 'update:visible']);
const formVisible = ref(false);

const rules = ref({
  name: [{ required: true, trigger: 'change', message: '请输入角色名' }],
  status: [{ required: true, trigger: 'change', message: '请选择状态' }],
});

const formData = ref({
  id: undefined,
  name: '',
  description: '',
  status: 1,
  dataScopeList: [],
  permIdList: [],
});

const permissionTreeData = ref([]);
const confirmLoading = ref<boolean>(false);
const checkedKeys = ref([]);

const { resetFields, validate, validateInfos } = useForm(formData, rules);
const getTitle = computed(() => (formData.value.id == undefined ? '新增角色' : '编辑角色'));

watch(
  () => formVisible.value,
  (val) => {
    emit('update:visible', val);
  },
);

watch(
  () => props.visible,
  (val) => {
    formVisible.value = val;
    if (val) {
      resetFields();
      deepMerge(formData.value, props.data);
      checkedKeys.value = [];
      formData.value.permIdList = [];
      if (formData.value.id) {
        fetchSelectedPermissionData(formData.value.id);
      }
    }
  },
);

const fetchData = async () => {
  permissionTreeData.value = await getPermissionList();
};

const fetchSelectedPermissionData = async (id) => {
  let list = await getPermissionListByRole({ roleId: id });
  if (list) {
    list.forEach((item) => {
      checkedKeys.value.push(item.id);
    });
    formData.value.permIdList = checkedKeys.value;
  }
};

const handlePermChecked = (checkedKeys, e) => {
  formData.value.permIdList = checkedKeys.checked;
};

onMounted(() => {
  fetchData();
});
const handleModalCancel = () => {
  formVisible.value = false;
};
const handleModalOK = async () => {
  try {
    confirmLoading.value = true;
    await validate();
    if (formData.value.id) {
      await updateRole(unref(formData));
    } else {
      await addRole(unref(formData));
    }
    message.success('保存成功');
    formVisible.value = false;
    emit('ok', true);
  } finally {
    confirmLoading.value = false;
  }
};
</script>